package com.psmz.iwi.docanalyzer.core.document.parser.word;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import com.psmz.iwi.docanalyzer.core.document.parser.Parser;
import com.psmz.iwi.docanalyzer.core.document.parser.ParserException;
import com.psmz.iwi.docanalyzer.core.document.parser.TextExtractionResult;

public class WordParser implements Parser {

	@Override
	public TextExtractionResult extractText(File file) throws ParserException {
		try {
			if (file.getName().endsWith(".doc")) {
				HWPFDocument document = new HWPFDocument(new FileInputStream(
						file));
				return new TextExtractionResult(document.getText().toString());
			} else if (file.getName().endsWith(".docx")) {
				XWPFDocument document = new XWPFDocument(new FileInputStream(
						file));
				XWPFWordExtractor extractor = new XWPFWordExtractor(document);
				return new TextExtractionResult(extractor.getText());
			} else {
				throw new IllegalArgumentException("To nie jest dokument word");
			}
		} catch (FileNotFoundException e) {
			System.err.println(e.toString());
			throw new ParserException("Plik nie istnieje", e);
		} catch (IOException e) {
			System.err.println(e.toString());
			throw new ParserException("Blad wejscia wyjscia", e);
		}
	}

}
